package com.fly.spring.mvc.configuration.spring;

import java.nio.charset.StandardCharsets;
import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 
 * 取代web.xml
 * 
 * @author 00fly
 * @version [版本号, 2021年3月27日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class WebXmlInitializer implements WebApplicationInitializer
{
    /**
     * web.xml 编码配置
     */
    @Override
    public void onStartup(ServletContext servletContext)
        throws ServletException
    {
        // 1、applicationContext
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(ApplicationConfiguration.class, SpringMvcConfiguration.class);
        servletContext.addListener(new ContextLoaderListener(applicationContext));
        
        // 2、CharacterEncodingFilter
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.toString());
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration filterRegistration = servletContext.addFilter("encodingFilter", characterEncodingFilter);
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        
        // 3、springmvc上下文
        Dynamic dynamic = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(applicationContext));
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/");
        
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();
    }
}
